package com.yixq.soa.service.web.auth.interceptor;

import com.alibaba.fastjson.JSONException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.TypeMismatchException;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;

import javax.servlet.http.HttpServletRequest;
import java.util.stream.Collectors;


/**
 * Created by zjp on 2017/4/19.
 */
@ControllerAdvice
public class GlobalExceptionHandler {

    private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    @ExceptionHandler(value = {BindException.class})
    public ResponseEntity<ErrorInfo> handleBeanBindException(HttpServletRequest req, BindException bindEx) {
        logger.error("参数绑定异常", bindEx);
        String allErroFields = bindEx.getBindingResult()
                .getFieldErrors()
                .stream()
                .map(FieldError::getField)
                .collect(Collectors.joining(",", "[", "]"));
        ErrorInfo err = new ErrorInfo("参数类型不正确或超出范围, 校验失败字段:" + allErroFields);
        return ResponseEntity.ok(err);
    }

    @ExceptionHandler(value = com.alibaba.fastjson.JSONException.class)
    public ResponseEntity<ErrorInfo> handleJsonException(HttpServletRequest req, JSONException jsonEx) {
        logger.error("参数类型不正确", jsonEx);
        ErrorInfo err = new ErrorInfo("参数类型不正确或超出范围");
        return ResponseEntity.ok(err);
    }

    @ExceptionHandler(value =  MethodArgumentTypeMismatchException.class)
    public ResponseEntity<ErrorInfo> handleMethodArgumentTypeMismatchException(HttpServletRequest req, Exception defaultEx) {
        ErrorInfo err = new ErrorInfo("请求参数类型不匹配");
        return ResponseEntity.ok(err);
    }

    @ExceptionHandler(value = {HttpRequestMethodNotSupportedException.class, TypeMismatchException.class})
    public ResponseEntity<ErrorInfo> handleHttpRequestMethodNotSupportedException(HttpServletRequest req, Exception defaultEx) {
        ErrorInfo err = new ErrorInfo("请求方式出错");
        return ResponseEntity.ok(err);
    }
    
    @ExceptionHandler(value = Exception.class)
    public ResponseEntity<ErrorInfo> handlDefaultException(HttpServletRequest req, Exception defaultEx) {
        logger.error("内部服务器错误", defaultEx);
        ErrorInfo err = new ErrorInfo("内部服务器错误");
        return ResponseEntity.ok(err);
    }
}
